<template>
  <h3 style="display: flex">实时温湿度:</h3>
  <el-row :gutter="20">
    <el-col :span="6" v-for="(item, index) in options" :key="index">
      <el-card :body-style="{ padding: '10px' }">
        <div slot="header" class="clearfix">
          <span>{{ item.label }}</span>
        </div>
        <div>
          温度：{{ realTimeData[item.label].temperature }}℃<br>
          湿度：{{ realTimeData[item.label].humidity }}%
        </div>
      </el-card>
    </el-col>
  </el-row>
  <el-button @click="fetchData">获取实时温湿度</el-button>
  <h3 style="display: flex">温湿度趋势:</h3>
  <el-row>
    <div class="block">
      <el-date-picker v-model="value2" type="datetimerange" :shortcuts="shortcuts" range-separator="To" start-placeholder="起始日期" end-placeholder="结束日期" />
    </div>
    <div class="block">
      <el-select v-model="value3" multiple placeholder="选择区域" style="width: 240px">
        <el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value.toString()" />
      </el-select>
    </div>
    <div class="block">
      <el-select v-model="value4" multiple placeholder="选择温度或湿度" style="width: 240px">
        <el-option label="温度" value="temperature" />
        <el-option label="湿度" value="humidity" />
      </el-select>
    </div>
  </el-row>
  <div>
    <div ref="chart" style="height: 500px; width: 1300px"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, toRef, toRefs } from "vue";
import * as echarts from "echarts"; //引入echarts核心模块
import axios from "axios"; //引入echarts核心模块
import { Search } from "@element-plus/icons-vue";
import { useRouter } from 'vue-router';
// import Index from "./views/index/index.vue";


const value2 = ref([]);


const shortcuts = [
  {
    text: "近1小时",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setHours(start.getHours() - 1);
      return [start, end];
    },
  },
  {
    text: "近3小时",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setHours(start.getHours() - 3);
      return [start, end];
    },
  },
  {
    text: "近一天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(start.getDate() - 1);
      return [start, end];
    },
  },
];
const chart = ref(); //创建dom引用

const series_data2 = ref();
const series_data = ref();
const series_data1 = ref();

const fetchData = async () => {
  for (const label in realTimeData.value) {
    realTimeData.value[label] = { temperature: '', humidity: '' };
  }

  const promises = [];
  console.log('数据获取中……')

  for (const option of options.value) {
    promises.push(getTemperature(option.temperatureStationId, option.label));
    promises.push(getHumidity(option.humidityStationId, option.label));
  }

  await Promise.all(promises);
};

const initChart = async() => {
  if (chart.value == null) {
    return;
  }

  echarts.dispose(chart.value);
  var myChart = echarts.init(chart.value);
  myChart.setOption({});

  let option = {
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        let result = '';
        params.forEach(param => {
          const stationId = param.seriesName.split(' ')[0]; 
          const dataType = param.seriesName.split(' ')[1]; 
          const stationName = stationNameMap[stationId] || stationId; 
          const time = formatDate(param.axisValue);
          result += `<span>${time} ${stationName} ${dataType}: ${param.data}</span><br/>`;
        });
        return result.trim();
      }
    },
    legend: {
      data: [],
      orient: 'vertical', 
      right: 10, 
      top: 'middle', 
      itemGap: 20
    },
    toolbox: {
      show: true,
      feature: {
        mark: { show: true },
        dataView: { show: true, readOnly: false },
        magicType: { show: true, type: ["line", "bar"] },
        restore: { show: true },
        saveAsImage: { show: true },
      },
    },
    
    title: {
      left: "center",
      subtext: "温度：℃  湿度：%",
      subtextStyle: {
        fontWeight: "bold",
      },
    },
    xAxis: {
      type: "category",
      data: series_data1.value,
    },
    dataZoom: [
      {
        type: "slider",
        start: 0,
        end: 100,
      },
      {
        type: "inside",
        start: 90,
        end: 100,
      },
    ],
    yAxis: [
      { 
        type: "value",
        name: '温度(℃)',
        position: 'left',
      },
      { 
        type: "value",
        name: '湿度(%)',
        min: 0,
        max: 100,
        interval: 10,
        position: 'right',
        axisLine: {
          lineStyle: {
            color: '#409EFF'
          }
        },
        axisLabel: {
          formatter: '{value} %'
        }
      }
    ],
    series: []
  };
  Object.keys(stationNameMap).forEach(stationId => {
    const stationName = stationNameMap[stationId];
    option.legend.data.push(`${stationName} 温度`);
    option.legend.data.push(`${stationName} 湿度`);
  });

  Object.entries(series_data.value).forEach(([stationId, data]) => {
    const stationName = stationNameMap[stationId];
    option.series.push({
      name: `${stationName} 温度`, 
      type: 'line',
      yAxisIndex: 0,
      data: data
    });
  });

  Object.entries(series_data2.value).forEach(([stationId, data]) => {
    const stationName = stationNameMap[stationId];
    option.series.push({
      name: `${stationName} 湿度`, 
      type: 'line',
      yAxisIndex: 1,
      data: data
    });
  });

  myChart.setOption(option);
};

onMounted(() => {
  const now = new Date();
  const start = new Date();
  const todayStart = start.setDate(start.getDate() - 1);
  value2.value = [todayStart, now];

  const stationFromUrl = router.currentRoute.value.query.station;
  if (stationFromUrl) {
    value3.value = stationFromUrl;
  }

  if (value2.value.length === 2 && value3.value) {
    use_show_data_in_html(); 
  }
});


const value3 = ref([]);
const value4 = ref([]);
const router = useRouter();
const { options } = toRefs({
  options: [
    { label: "装配南", temperatureStationId: "IJ.Channel_1.7116.UAV5", humidityStationId: "IJ.Channel_1.7116.AV14", temperature: "", humidity: "" },
    { label: "装配北", temperatureStationId: "IJ.Channel_1.7116.UAV6", humidityStationId: "IJ.Channel_1.7116.AV15", temperature: "", humidity: "" },
    { label: "缸体M1", temperatureStationId: "IJ.Channel_1.7116.UAV2", humidityStationId: "IJ.Channel_1.7116.AV11", temperature: "", humidity: "" },
    { label: "缸体M2", temperatureStationId: "IJ.Channel_1.7116.UAV3", humidityStationId: "IJ.Channel_1.7116.AV12", temperature: "", humidity: "" },
    { label: "缸盖M1", temperatureStationId: "IJ.Channel_1.7116.UAV0", humidityStationId: "IJ.Channel_1.7116.UAV9", temperature: "", humidity: "" },
    { label: "缸盖M2", temperatureStationId: "IJ.Channel_1.7116.UAV1", humidityStationId: "IJ.Channel_1.7116.AV10", temperature: "", humidity: "" },
    { label: "曲轴M1", temperatureStationId: "IJ.Channel_1.7116.UAV4", humidityStationId: "IJ.Channel_1.7116.AV13", temperature: "", humidity: "" },
  ]
});

const {options2} = toRefs({
    options2:[
    {value: ['IJ.Channel_1.7116.UAV5','IJ.Channel_1.7116.AV14'],label: "装配南",temperature: "", humidity: ""},
    {value: ['IJ.Channel_1.7116.UAV6','IJ.Channel_1.7116.AV15'],label: "装配北",temperature: "", humidity: ""},
    {value: ["IJ.Channel_1.7116.UAV2","IJ.Channel_1.7116.AV11"],label: "缸体M1",temperature: "", humidity: ""},
    {value: ["IJ.Channel_1.7116.UAV3","IJ.Channel_1.7116.AV12"],label: "缸体M2",temperature: "", humidity: ""},
    {value: ["IJ.Channel_1.7116.UAV0","IJ.Channel_1.7116.UAV9"],label: "缸盖M1",temperature: "", humidity: ""},
    {value: ["IJ.Channel_1.7116.UAV1","IJ.Channel_1.7116.AV10"],label: "缸盖M2",temperature: "", humidity: ""},
    {value: ["IJ.Channel_1.7116.UAV4","IJ.Channel_1.7116.AV13"],label: "曲轴",temperature: "", humidity: ""},
  ]
  });

const stationNameMap = {
  'IJ.Channel_1.7116.UAV5,IJ.Channel_1.7116.AV14': '装配南',
  'IJ.Channel_1.7116.UAV6,IJ.Channel_1.7116.AV15': '装配北',
  'IJ.Channel_1.7116.UAV2,IJ.Channel_1.7116.AV11': '缸体M1',
  'IJ.Channel_1.7116.UAV3,IJ.Channel_1.7116.AV12': '缸体M2',
  'IJ.Channel_1.7116.UAV0,IJ.Channel_1.7116.UAV9': '缸盖M1',
  'IJ.Channel_1.7116.UAV1,IJ.Channel_1.7116.AV10': '缸盖M2',
  'IJ.Channel_1.7116.UAV4,IJ.Channel_1.7116.AV13': '曲轴'
};

function formatDate(d: string) {
  var date = new Date(d);
  var YY = date.getFullYear() + "-";
  var MM = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
  var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  var hh = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
  var mm = (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + ":";
  var ss = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  return YY + MM + DD + " " + hh + mm + ss;
}

const realTimeData = ref({
  '装配南': { temperature: '', humidity: '' },
  '装配北': { temperature: '', humidity: '' },
  '缸体M1': { temperature: '', humidity: '' },
  '缸体M2': { temperature: '', humidity: '' },
  '缸盖M1': { temperature: '', humidity: '' },
  '缸盖M2': { temperature: '', humidity: '' },
  '曲轴M1': { temperature: '', humidity: '' },

});

const updateRealTimeData = (label: string, newData: { temperature?: number, humidity?: number }) => {
  if (realTimeData.value[label]) {
    realTimeData.value[label] = { ...realTimeData.value[label], ...newData };
  }
};

const getTemperature = async (stationId: string, label: string) => {
  const url = `http://10.64.35.32:8000/temperature_analysis/get_temperature_data/?start_time=${formatDate(new Date().setMinutes(new Date().getMinutes() - 15))}&end_time=${formatDate(new Date())}&xtagname=${stationId}&page_size=1`;
  try {
    const response = await axios.get(url);
    const temperature = response.data[0]?.xvalue;
    console.log('url', url)
    console.log('区域', stationId);
    console.log('实时温度', temperature);
    updateRealTimeData(label, { temperature });
  } catch (error) {
    console.error('Error fetching temperature:', error);
  }
};

const getHumidity = async (stationId: string, label: string) => {
  const url = `http://10.64.35.32:8000/temperature_analysis/get_temperature_data/?start_time=${formatDate(new Date().setMinutes(new Date().getMinutes() - 15))}&end_time=${formatDate(new Date())}&xtagname=${stationId}&page_size=1`;
  try {
    const response = await axios.get(url);
    const humidity = response.data[0]?.xvalue;
    updateRealTimeData(label, { humidity });
  } catch (error) {
    console.error('Error fetching humidity:', error);
  }
};

const updateStationData = (stationId: string, newData: { temperature?: number, humidity?: number }) => {
  options2.value = options2.value.map(item => {
    if (item.value.includes(stationId)) {
      console.log('Updating station:', stationId, 'with data:', newData);
      return { ...item, ...newData };
    }
    return item;
  });
};

const show_data_in_html = async (url: string, stationId: string) => {
  axios.get(url).then((res) => {
    const data = res.data.map((item: any) => item.xvalue);
    const timestamps = res.data.map((item: any) => item.xtimestamp);

    if (!series_data1.value.length) {
      series_data1.value = timestamps;
    } else if (timestamps.length !== series_data1.value.length) {
      console.error('Timestamp length mismatch');
      return;
    }
    series_data.value[stationId] = data;
    initChart();
  });
};


const show_data_in_html_humidity = async (url: string, stationId: string) => {
  axios.get(url).then((res) => {
    const data = res.data.map((item: any) => item.xvalue);
    const timestamps = res.data.map((item: any) => item.xtimestamp);

    if (!series_data1.value.length) {
      series_data1.value = timestamps;
    } else if (timestamps.length !== series_data1.value.length) {
      console.error('Timestamp length mismatch');
      return;
    }
    series_data2.value[stationId] = data;
    initChart();
  });
};

watch([value2, value3, value4], async () => {
  await use_show_data_in_html();
});

const use_show_data_in_html = async () => {
  if (value4.value.includes('temperature') || value4.value.includes('humidity')) {
    series_data.value = {};
    series_data2.value = {};
    series_data1.value = [];

    for (let i = 0; i < value3.value.length; i++) {
      const stationId = value3.value[i].split(','); 

      const temperatureUrl = `http://10.64.35.32:8000/temperature_analysis/get_temperature_data/` +
                             `?start_time=${formatDate(value2.value[0])}` +
                             `&end_time=${formatDate(value2.value[1])}` +
                             `&xtagname=${stationId[0]}` +
                             `&page_size=10001`;
      console.log('tem', temperatureUrl)
      if (value4.value.includes('temperature')) {
        await show_data_in_html(temperatureUrl, stationId);
      }

      const humidityUrl = `http://10.64.35.32:8000/temperature_analysis/get_temperature_data/` +
                          `?start_time=${formatDate(value2.value[0])}` +
                          `&end_time=${formatDate(value2.value[1])}` +
                          `&xtagname=${stationId[1]}` +
                          `&page_size=10001`;
      console.log('hum', humidityUrl)
      if (value4.value.includes('humidity')) {
        await show_data_in_html_humidity(humidityUrl, stationId);
      }
    }

    initChart();
  }
};
</script>

<style scoped>
h3 {
  color: black;
}

.block {
  padding: 20px;
  text-align: center;
  flex: 1;
}
.block:last-child {
  border-right: none;
}
.block .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
.el-select .el-scrollbar__wrap {
  max-height: 50px !important; 
  overflow-y: auto !important; 
}
</style>

